<?php
/**
 * @title 50. Pow(x, n) - 二进制
 * @author start2004
 */

class Solution {

    /**
     * @param Float $x
     * @param Integer $n
     * @return Float
     */
    function myPow($x, $n) {
        /**
         * @since 2020-07-22 极端情况排除
         */
        if($n == 0){
            return 1;
        } else {}

        /**
         * @since 2020-07-29 负数标记
         */
        $minus = false;
        if($n<0){
            $minus = true;
            $n = 0-$n;
        } else {}

        /**
         * @since 2020-07-29 结果集
         */
        $result = 1;

        /**
         * @since 2020-07-29 二进制
         */
        $bin = strval(decbin($n));
        for($i=strlen($bin)-1; $i>=0; $i--){
            if($bin[$i] == "1"){
                $result *= $x;
            } else {}
            $x = $x*$x;
        }

        /**
         * @since 2020-07-29 负数处理
         */
        if($minus){
            $result = 1/$result;
        } else {}

        /**
         * @return
         */
        return $result;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.22_6.php
 */
$datas = [
    [2.00000, 10],
    [2.10000, 3],
    [2.00000, -2],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->myPow($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
